package com.llxwz.controller;


import com.llxwz.entity.Page;
import com.llxwz.entity.User;
import com.llxwz.service.FollowService;
import com.llxwz.service.LikeService;
import com.llxwz.service.UserService;
import com.llxwz.util.CommunityConstant;
import com.llxwz.util.CommunityUtil;
import com.llxwz.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController implements CommunityConstant {

    @Value("${community.path.domain}")
    private String domain;

    @Value("${community.path.upload}")
    private String upload;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;


    //去账号设置界面
    //@LoginRequired
    @GetMapping("/setting")
    public String setting(){
        return "site/setting";
    }

    @GetMapping("/setSign")
    public String setSign(){
        return "site/setSign";
    }


    //更新头像
    //@LoginRequired
    @PostMapping("/upload")
    public String changeHeadUrl(MultipartFile multipartFile, Model model){

        if(multipartFile==null){
            model.addAttribute("error","你没有选择图片");
            return "site/setting";
        }
        //获取用户选择上传文件的文件名
        String filename = multipartFile.getOriginalFilename();
        //获取文件名的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //后缀可能为空
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式名不对");
            return "site/setting";
        }
        //由于要存入服务器中，避免命名在服务器的文件下冲突
        filename = CommunityUtil.generateUUID()+suffix;
        //设置服务器文件的本地地址
        File dest = new File(upload+"/"+filename);
        //将用户上传的文件存入服务器本地
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            //logger
            e.printStackTrace();
            throw new RuntimeException("上传文件失败，服务器发生异常");
        }

        //更新当前用户的头像的路径(web访问路径)
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/header/" + filename;
        userService.changeHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }

    //查看用户头像
    @GetMapping("/header/{filename}")
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response){
        //设置服务器本地文件名
        filename = upload + "/" + filename;
        //获取文件名后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //设置响应文件格式
        response.setContentType("image/"+suffix);
        //读取本地文件
        try(
                FileInputStream inputStream = new FileInputStream(filename);
                OutputStream os = response.getOutputStream();
                )
        {
            byte[] buffer = new byte[1024];
            int b=0;
            while ((b = inputStream.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    //@LoginRequired
    @PostMapping("/uppwd")
    public String uppwd(String oldpwd,String newpwd,String renewpwd,Model model){

        User user = hostHolder.getUser();

        String old = CommunityUtil.md5(oldpwd+user.getSalt());
        if(!user.getPassword().equals(old)){
            model.addAttribute("oldMsg","与原密码不同");
            return "site/setting";
        }


        if(newpwd.equals(oldpwd)){
            model.addAttribute("newMsg","新密码与原密码一样");
            return "site/setting";
        }

        if(!newpwd.equals(renewpwd)){
            model.addAttribute("renewMsg","两次密码不同");
            return "site/setting";
        }

        newpwd = CommunityUtil.md5(newpwd+user.getSalt());
        userService.changePassword(user.getId(),newpwd);

        return "redirect:/index";
    }

    @PostMapping("/upSign")
    public String upSign(String sign){
        User user = hostHolder.getUser();
        userService.changeSign(user.getId(),sign);
        return "site/setSign";
    }

    @PostMapping("/upPhone")
    public String upPhone(String phone,Model model){

        if (CommunityUtil.isPhoneInvalid(phone)) {
            model.addAttribute("error","手机号格式错误！");
            return "site/setSign";
        }
        User user = hostHolder.getUser();
        userService.changePhone(user.getId(),phone);
        return "site/setSign";
    }


    @GetMapping("/getUsers/{username}/{type}/{status}")
    public String getUsers(@PathVariable("username")String username,
                           @PathVariable("type")int type,
                           @PathVariable("status")int status,
                           Model model, Page page){

        page.setRows(userService.getUserCount(username,type,status));
        page.setPath("/getUsers/"+username+"/"+type+"/"+status);

        List<User> users = userService.getUsers(username,type, status, page.getCurrent(), page.getLimit());

        if(users!=null){
            model.addAttribute("users",users);
        }

        return "site/admin/userList";
    }

    @PostMapping("/setUser")
    public String setUser(int id,int type,int status){

        userService.setType(id,type);
        userService.setStatus(id,status);
        return "redirect:/getUsers/null/-1/-1";
    }
    //封号
    @PostMapping("/banUser")
    public String ban(int id) {
        userService.setStatus(id,2);
        return "redirect:/getUsers/null/-1/-1";
    }

    //解封
    @PostMapping("/unbanUser")
    public String unban(int id) {
        userService.setStatus(id,1);
        return "redirect:/getUsers/null/-1/-1";
    }

    //个人主页
    @GetMapping("/profile/{userId}")
    public String profile(@PathVariable("userId")int userId,Model model){
        User user = userService.findById(userId);
        if(user == null){
            throw new RuntimeException("该用户不存在");
        }
        //用户
        model.addAttribute("user",user);
        //被点赞的数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        model.addAttribute("followerCount",followerCount);
        //当前用户是否已关注该用户
        boolean hasFollowed = false;
        if(hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);

        return "site/profile";
    }


}
